import QtQuick 1.1
import com.nokia.meego 1.1
import "ProjectLatLon.js" as ProjectLatLon

Page {    
	id: buienradarPage
	orientationLock: PageOrientation.LockPortrait

	PageHeader {
		id: header
        text: qsTr("Buienradar")
	}

	Label {
		id: radarLoadingLabel
        text:  radarImage.status != Image.Error ? qsTr("Ophalen buienkaart...") : qsTr("Fout bij ophalen buienkaart")
		anchors.horizontalCenter: parent.horizontalCenter
		anchors.verticalCenter: parent.verticalCenter
		visible: radarImage.status != Image.Ready
	}

	ProgressBar {
		minimumValue: 0.0
		maximumValue: 1.0
		indeterminate: radarImage.progress == 0
		value: radarImage.progress
		visible: radarLoadingLabel.visible && radarImage.status != Image.Error
		anchors.horizontalCenter: parent.horizontalCenter
		anchors.top: radarLoadingLabel.bottom
		width: parent.width * 0.75
		anchors.margins: UiConstants.DefaultMargin
	}

	// Frame for (zoomed) image.
	// A Flickable would be a better match, however, it doesn't seem to play
	// nice i.c.w. the PinchArea. Using a MouseArea for dragging instead.
	Item {
		id: imageFrame
		anchors {
			top: header.bottom
			left: parent.left
			right: parent.right
			topMargin: 30
		}

		height: 448

		clip: true

		// Wraps the image and place marker, so they are scaled at the same time
		Item {
			id: radarWrapper
			width: parent.width
			height: parent.height
			property real markerX: ProjectLatLon.X(settings.latitude, settings.longitude) * (480 / 700)
			property real markerY: (-ProjectLatLon.Y(settings.latitude, settings.longitude) - 3727) * (480 / 700)

			function setPos(xIn, yIn) {
				var effectiveXOffset = radarImage.paintedWidth * (scale - 1) * 0.5;
				var effectiveYOffset = radarImage.paintedHeight * (scale - 1) * 0.5;

				x = Math.max(Math.min(xIn, effectiveXOffset), -effectiveXOffset);
				y = Math.max(Math.min(yIn, effectiveYOffset), -effectiveYOffset);
			}

			AnimatedImage {
				id: radarImage
                property string url: "http://buienradar.mobi/image.ashx?c=nl&k=0&step=0&w=480&h=448"

				function reload() {
					source = url + "#" + Date.now();
					// Reset position
					radarWrapper.x = 0;
					radarWrapper.y = 0;
				}

				source: url
				smooth: true
				width: parent.width
				height: parent.height
				onFrameChanged: {
					if (!frameSlider.pressed) {
						frameSlider.value = currentFrame;
					}
				}

				// Don't animate of animation isn't visible
				playing: appVisible && buienradarPage.visible && !frameSlider.pressed

				// Don't waste cache on image that is stale within 5 minutes anyway
				cache: false
			}

			Image {
				id: marker
				source: "marker.svg"
				scale: 1/radarWrapper.scale
				smooth: true
				// Note: ProjectLatLon returns its values in km from the origin (90 lat, 0 lon).
				// Map these values to the correct position on the map
				x: radarWrapper.markerX - (width / 2)
				y: radarWrapper.markerY - (height / 2)
			}

			states: [
				State {
					when: settings.compassMode == 0
					PropertyChanges { target: radarWrapperTransform; angle: 0 }
				},
				State {
					when: settings.compassMode == 1
					PropertyChanges { target: compass; active: appVisible && buienradarPage.visible }
					PropertyChanges { target: compass; onReadingChanged: marker.rotation = reading.azimuth - settings.longitude }
					PropertyChanges { target: marker; source: "markerArrow.svg" }
					PropertyChanges { target: radarWrapperTransform; angle: 0 }
				},
				State {
					when: settings.compassMode == 2
					PropertyChanges { target: compass; active: appVisible && buienradarPage.visible }
					PropertyChanges { target: compass; onReadingChanged: radarWrapperTransform.angle = -(reading.azimuth - settings.longitude) }
				}
			]

			scale: radarImage.status == Image.Ready ? 1 : 0

			transform: Rotation {
				id: radarWrapperTransform
				// Rotate around the marker, instead of the center of the map.
				origin.x: (radarWrapper.markerX - (radarImage.width / 2)) * radarWrapper.scale + radarImage.width / 2
				origin.y: (radarWrapper.markerY - (radarImage.height / 2)) * radarWrapper.scale + radarImage.height / 2
				Behavior on angle {
					RotationAnimation {
						direction: RotationAnimation.Shortest
						easing.type: Easing.InOutQuad
						duration: 200
					}
				}
			}

			Behavior on scale {
				NumberAnimation {
					easing.type: Easing.InQuad
					duration: 300
				}
			}
		}

		PinchArea {
			pinch.target: radarWrapper
			anchors.fill: parent
			pinch {
				// BUG: dragging with a PinchArea in portrait seems to have x and y coords swapped. Unusable!
				dragAxis: Pinch.NoDrag
				minimumScale: 1
				maximumScale: 3
			}

			onPinchUpdated: {
				radarWrapper.setPos(radarWrapper.x, radarWrapper.y);
			}
		}

		MouseArea {
			property bool __isPanning: false
			property int __lastX: -1
			property int __lastY: -1

			anchors.fill : parent

			onPressed: {
				__isPanning = true
				__lastX = mouse.x
				__lastY = mouse.y
			}

			onReleased: {
				__isPanning = false
			}

			onPositionChanged: {
				if (__isPanning) {
					var dx = mouse.x - __lastX
					var dy = mouse.y - __lastY

					radarWrapper.setPos(radarWrapper.x + dx, radarWrapper.y + dy);

					__lastX = mouse.x
					__lastY = mouse.y
				}
			}

			onCanceled: {
				__isPanning = false;
			}
		}
	}

	Slider {
		id: frameSlider
		minimumValue: 0
		maximumValue: 13 // BUG: Aparantly, in Qt 4.7.4 frameCount doesn't emit a signal when changed:(
		stepSize: 1

		// Number of first frame that represents "the future"
		property int prognosisFrame: Math.round(maximumValue / 2)

		anchors {
			top: imageFrame.bottom
			horizontalCenter: parent.horizontalCenter
		}

		// Make slider not too wide, to avoid accidental swiping.
		width: parent.width * 0.85

		onValueChanged: {
			if (pressed) {
				radarImage.currentFrame = value
			}
		}

		// Change the slider background when the animation shows the prognosis
		platformStyle: SliderStyle {
			grooveItemBackground: "image://theme/color" + (radarImage.currentFrame >= frameSlider.prognosisFrame ? 15 : 7) + "-meegotouch-slider-elapsed-background-horizontal"
			grooveItemElapsedBackground: "image://theme/color" + (radarImage.currentFrame >= frameSlider.prognosisFrame ? 15 : 7) + "-meegotouch-slider-elapsed-background-horizontal"
		}

		visible: radarImage.status == Image.Ready
		valueIndicatorText: ((value - prognosisFrame) > 0 ? "+" : "") + (value - prognosisFrame) * 5 + " min"
		valueIndicatorVisible: true
	}

	Item {
		visible: frameSlider.visible

		anchors {
			left: parent.left
			right: parent.right
			top: frameSlider.bottom
			topMargin: -10
		}

		Text {
            text: qsTr("Verleden")
			anchors.right: nu.left
			font.pixelSize: 15
			anchors.rightMargin: 20
		}

		Text {
			id: nu
			text: "|"
			anchors.horizontalCenter: parent.horizontalCenter
			font.pixelSize: 15
		}

		Text {
			anchors.left: nu.right
			anchors.leftMargin: 20
            text: qsTr("Toekomst")
			font.pixelSize: 15
		}
	}

	ToolIcon {
		id: refreshButton
		iconId: "toolbar-refresh"
		anchors.horizontalCenter: parent.horizontalCenter
		anchors.bottom: parent.bottom
		onClicked: radarImage.reload()
		visible: radarImage.status == Image.Ready || radarImage.status == Image.Error
	}
}
